<template>
  <div class="container">
    <div>
      <el-row :gutter="25">
        <el-col :span="6">
          <el-form ref="form" :model="form" label-width="220">
            <el-form-item label="处理站名称：">
              <el-input v-model="select.name" placeholder="请输入处理站名称" style="width:7.813vw;"></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="14">
          <el-form ref="form" :model="form" style="float:left">
            <el-form-item>
              <el-button size="mini" type="primary" @click="screeningData">查 询</el-button>
              <el-button size="mini" type="success" @click="handleAdd">新 增</el-button>

              <el-button style="padding:0;border:0">
              <el-upload
                  action="/上传文件的接口"
                  :on-change="onChange"
                  :auto-upload="false"
                  :show-file-list="false"
                  accept=".xls, .xlsx"
                  class="upload"
              >
                <el-button size="mini" type="success" >导 入</el-button>
              </el-upload>
              </el-button>
              <el-button size="mini" type="warning" @click="exportExcel">导 出</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <el-table highlight-current-row :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)" @row-dblclick="dblClickRow">
      <el-table-column  prop="ID" label="处理站编号" align="center" ></el-table-column>
      <el-table-column  prop="NAME" label="处理站名称" align="center"></el-table-column>
      <!-- <el-table-column  prop="LONGITUDE" label="经度" align="center"></el-table-column>
      <el-table-column  prop="LATITUDE" label="纬度" align="center"></el-table-column> -->
      <el-table-column  prop="LOCATION" label="定位信息" align="center"></el-table-column>
      <el-table-column  prop="NUMBER" label="额定处理量" align="center" ></el-table-column>
      <el-table-column  prop="COMPANY" label="工艺类型" align="center"></el-table-column>
      <!-- <el-table-column  prop="CLIENT_NO" label="区域ID" align="center"></el-table-column> -->
      <el-table-column  prop="TYPE" label="运行单位" align="center"></el-table-column>
      <el-table-column  prop="THEORY" label="联系人" align="center"></el-table-column>
      <el-table-column  prop="THEORY" label="联系电话" align="center"></el-table-column>
      <el-table-column label="操作" width="180" align="center" >
        <template slot-scope="scope">
          <!-- <el-button type="text" @click="handleEdit(scope.$index, scope.row)"
            >定位</el-button
          > -->
          <el-button type="text" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            @click="handleDelete(scope.$index, scope.row)"
            style="color: red"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.length"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>
    <!-- 弹出框 -->
    <el-dialog
      :title="addDialogTitle"
      :visible.sync="isVisibleEdit"
      width="50%"
      :modal="false"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        label-width="6.2vw"
        class="flex"
      >
        <el-form-item label="处理站名称：" class="wid50">
          <el-input
            v-model="form.NAME"
            placeholder="请输入处理站名称"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="经度：" class="wid50">
          <el-input
            v-model="form.LONGITUDE"
            placeholder="请输入经度"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="纬度：" class="wid50">
          <el-input
            v-model="form.LATITUDE"
            placeholder="请输入纬度"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="位置：" class="wid50">
          <el-input
            v-model="form.LOCATION"
            placeholder="请输入位置"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="处理站垃圾处理原理：" class="wid50">
          <el-input
            v-model="form.THEORY"
            placeholder="请输入处理站垃圾处理原理"
            class="handle-input mr10"
          ></el-input>
        </el-form-item> -->
        <el-form-item label="处理站日处理量：" class="wid50">
          <el-input
            v-model="form.NUMBER"
            placeholder="请输入处理站日处理量"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="处理站所属公司：" class="wid50">
          <el-input
            v-model="form.COMPANY"
            placeholder="请输入处理站所属公司"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="处理站类型：" class="wid50">
          <el-select
            v-model="form.TYPE"
            placeholder="请选择"
            @change="changClient"
          >
            <el-option
              v-for="item in TYPElevel"
              :key="item.TYPEltitle"
              :label="item.TYPEltitle"
              :value="item.TYPEltitle"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="组织级别：" class="wid50">
          <el-select
            v-model="form.CTYPE"
            placeholder="请选择"
            @change="changClient"
          >
            <el-option
              v-for="item in rolelevel"
              :key="item.rolelevelindex"
              :label="item.roleleveltitle"
              :value="item.rolelevelindex"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="组织机构：" class="wid50">
          <el-select
            v-model="form.CLIENT_NO"
            value-key="id"
            placeholder="请选择"
          >
            <el-option
              v-for="item in selectClientInfoList"
              :key="item.CLIENT_NO"
              :label="item.CLIENT_NAME"
              date-name="item.CLIENT_NAME"
              :value="item.CLIENT_NO"
            >
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit()">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import '@/assets/css/common.css'

import export2Excel from '@/utils/exportExcel/index.js'
import { time } from 'echarts'
import eventBus from '@/eventBus.js'

export default {
  data () {
    return {
      clientData: [],
      currentPage: 1, // 初始页
      pageSize: 10, //    每页的数据
      originalData: [],
      tableData: [],
      expireData: [],
      select: {
        name: ''
      },
      isVisibleEdit: false,
      showBigDialogDate: true,
      selectClientInfoList: [],
      TYPElevel: [
        { TYPEltitle: '其他垃圾处理站' },
        { TYPEltitle: '厨余垃圾处理站' },
        { TYPEltitle: '可回收垃圾处理站' },
        { TYPEltitle: '有害垃圾处理站' }
      ],
      rolelevel: [{
        roleleveltitle: '公司',
        rolelevelindex: '-1'
      }, {
        roleleveltitle: '项目',
        rolelevelindex: '0'
      }, {
        roleleveltitle: '机扫',
        rolelevelindex: '1'
      }, {
        roleleveltitle: '垃圾',
        rolelevelindex: '2'
      }, {
        roleleveltitle: '人工',
        rolelevelindex: '3'
      }, {
        roleleveltitle: '公厕维保',
        rolelevelindex: '4'
      }],
      form: {
        DW: '',
        CPH: '',
        MODEL: '',
        PERSON: '',
        BUYTIME: '',
        EXPLAIN: '',
        USEDEPTNAME: '',
        USEDEPTID: '',
        VOWNER: '',
        BRAND: '',
        VIN: '',
        ENGINENUM: '',
        DISCHARGERATE: '',
        VCONDITION: '',
        PRICE: '',
        CLIENT_NO: [],
        USE: ''
      },
      showBigDialogVisible: false,
      srcBig: ''
    }
  },
  created () {
    if (localStorage.getItem('CTYPE') === '0') {
      this.rolelevel.shift()
    } else if (localStorage.getItem('CTYPE') !== '-1') {
      this.rolelevel = []
    }
    this.getClientRoleList()
  },
  mounted () {
    // this.getlistdata()
    // this.screeningData()
  },
  methods: {
    // 获取处理站列表
    async getlistdata1 () {
      var url = '/CarService/getPlaceFactory?CLIENT_NO=' + localStorage.getItem('CLIENT_NO')
      const { data } = await this.$Http.get(url)
      this.originalData = data
      this.screeningData()
    },
    // 获取组织机构名
    async getClientRoleList () {
      var url = '/CarService/getAbleAddPlaceInfo?CLIENT_NO=' + localStorage.getItem('CLIENT_NO')
      const { data } = await this.$Http.get(url)
      this.selectClientInfoList = data
    },
    // 给组织机构名称下拉列表传值
    changClient (e) {
      this.form.CLIENT_NO_select = ''
      this.getClientRoleList(e)
    },
    change (e) {
      this.$forceUpdate()
    },
    // 导入Excel
    onChange1 (file, fileList) {
      //  console.log(fileList);
      this.fileData = file // 保存当前选择文件
      this.readExcel() // 调用读取数据的方法
    },
    // 读取数据
    readExcel (e) {
      const that = this
      const files = that.fileData
      console.log(files)
      if (!files) {
        // 如果没有文件
        return false
      } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
        this.$message.error('上传格式不正确，请上传xls或者xlsx格式')
        return false
      }
      const fileReader = new FileReader()
      console.log(fileReader)
      fileReader.onload = ev => {
        try {
          const data = ev.target.result
          //  console.log(ev.target)
          //  console.log(this);
          const workbook = this.XLSX.read(data, {
            type: 'binary'// 以字符编码的方式解析
          })

          if (workbook.SheetNames.length >= 1) {
            //  this.$message({
            //    message: "导入数据表格成功",
            //    showClose: true,
            //    type: "success"
            //  });

            const wsname = workbook.SheetNames[0] // 取第一张表
            const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) // 生成json表格内容
            console.log(ws)
            this.inputExcelDataLength = ws.length
            this.fullscreenLoading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            for (let i = 0, len = ws.length; i < len; i++) {
              var item = ws[i]
              //   var sheetData = {
              //     VID: item['居民电话'],
              //     RUBBISH_NAME: item["垃圾品名"],
              //     WEIGHT: item["垃圾称重"],
              //     photo: '',
              //     LONGITUDE: 0,
              //     LATITUDE: 0
              //   }
              //   let exceldata =  []
              //   exceldata.push(sheetData)
              this.addWeight(item)
            }
          } else {
            this.$message.error('未读取到表格内容')
          }
        } catch (e) {
          return false
        }
      }
      // 如果为原生 input 则应是 files[0]
      fileReader.readAsBinaryString(files.raw)
    },
    async addWeight (item) {
      this.$axios({
        url: 'CarService/AddPlaceFactory',
        method: 'post',
        data: {
          NAME: item['处理站名称'],
          LONGITUDE: item['经度'],
          LATITUDE: item['纬度'],
          LOCATION: item['位置'],
          THEORY: item['处理站垃圾处理原理'],
          NUMBER: item['处理站日处理量'],
          COMPANY: item['处理站所属公司'],
          TYPE: item['处理站类型'],
          CLIENT_NO: item['区域ID']
        }
      }).then(res => {
        console.log(res)
        this.inputExcelDataIndex++
        if (res.data.IsSucess) {
          this.fullscreenLoading.close()
          this.$message.success('表格文件导入成功')
          this.getlistdata()
        } else {
          this.fullscreenLoading.close()
          this.$message.error('表格文件导入失败' + '，' + res.data.Message)
        }
        if (this.inputExcelDataIndex === this.inputExcelDataLength) {
          this.fullscreenLoading.close()
          if (this.strError.length === 0) {
            this.$message.success('表格文件导入成功')
          } else {
            // this.$message.error('表格文件导入结束<br/>' + this.strError);
            this.$message({
              message: '表格文件导入结束，' + this.strError,
              type: 'error',
              duration: 5000
            })
          }
          this.getlistdata()
        }
      })
      //   })
    },
    // 导出Excel
    exportExcel () {
      const excelName = '处理站信息'
      const tHeader = ['处理站编号', '处理站名称', '经度', '纬度', '位置', '处理站垃圾处理原理', '处理站日处理量', '处理站所属公司', '处理站类型', '区域ID']
      const filterVal = ['ID', 'NAME', 'LONGITUDE', 'LATITUDE', 'LOCATION', 'THEORY', 'NUMBER', 'COMPANY', 'TYPE', 'CLIENT_NO']
      export2Excel(tHeader, filterVal, this.tableData, excelName)
    },
    // 打开新增窗口
    handleAdd () {
      this.addDialogTitle = '新增处理站信息'
      // 清空编辑框
      this.form = {}
      // 展示窗口
      this.isVisibleEdit = true
      // this.idEdit = false;
    },
    // 打开编辑窗口
    handleEdit (index, row) {
      this.form = Object.assign({}, row)
      this.form.CLIENT_NO_select = this.form.USERNAME
      this.addDialogTitle = '编辑处理站信息'
      this.isVisibleEdit = true
    },
    // 点击保存，判断是新增还是编辑操作
    handleSubmit () {
      if (this.addDialogTitle === '新增处理站信息') {
        this.saveAdd()
      } else {
        this.saveEdit()
      }
    },
    // 新增保存
    async saveAdd1 () {
      // console.log(this.addform)
      this.$axios({
        url: 'CarService/AddPlaceFactory',
        method: 'post',
        data: {
          NAME: this.form.NAME,
          LONGITUDE: this.form.LONGITUDE,
          LATITUDE: this.form.LATITUDE,
          LOCATION: this.form.LOCATION,
          THEORY: this.form.THEORY,
          NUMBER: this.form.NUMBER,
          COMPANY: this.form.COMPANY,
          TYPE: this.form.TYPE,
          CLIENT_NO: this.form.CLIENT_NO
        }

      }).then((res) => {
        console.log(this.data)
        console.log(res)
        if (res.data.IsSucess) {
          this.$message.success('新增成功')
          this.isVisibleEdit = false
          this.getlistdata()
        } else {
          this.$message.error('新增失败')
        }
      })
    },
    // 保存编辑
    async saveEdit () {
      this.$axios({
        url: 'CarService/UpdataPlaceFactory',
        method: 'post',
        data: {
          ID: this.form.ID,
          NAME: this.form.NAME,
          CPH: this.form.CPH,
          LONGITUDE: this.form.LONGITUDE,
          LATITUDE: this.form.LATITUDE,
          LOCATION: this.form.LOCATION,
          THEORY: this.form.THEORY,
          NUMBER: this.form.NUMBER,
          COMPANY: this.form.COMPANY,
          TYPE: this.form.TYPE,
          CLIENT_NO: this.form.CLIENT_NO
        }

      }).then((res) => {
        console.log(this.data)
        console.log(res)
        if (res.data.IsSucess) {
          this.$message.success('编辑成功')
          this.isVisibleEdit = false
          this.getlistdata()
        } else {
          this.$message.error('编辑失败')
        }
      })
    },
    // 删除处理站信息
    async handleDelete (index, row) {
      const confirmResult = await this.$confirm('确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult === 'confirm') {
        const params = {
          ID: row.ID
        }
        const { data } = await this.$Http.get('CarService/DeletePlaceFactory', { params })
        if (data.IsSucess) {
          this.$message.success('删除成功')
          this.isVisibleEdit = false
          this.getlistdata()
        } else {
          this.$message.error('删除失败')
        }
      } else {
        this.$message.info('取消删除')
        this.isVisibleEdit = false
      }
    },
    // 模糊查询
    screeningData () {
      this.currentPage = 1
      this.tableData = []
      // this.tableData = this.originalData
      // if (this.select.name) this.tableData = this.tableData.filter(item => item.NAME.includes(this.select.name))
      // console.log(this.select.name)
      var listChuyu = []; var listQita = []; var listKehuishou = []; var listYouhai = []
      this.originalData.forEach(item => {
        if (!item.NAME.includes(this.select.name)) {
          return
        }
        switch (item.TYPE) {
          case '厨余垃圾处理站': {
            item.img = '厨余垃圾'
            listChuyu.push(item)
            break
          }
          case '其他垃圾处理站': {
            item.img = '其他垃圾'
            listQita.push(item)
            break }
          case '可回收垃圾处理站': {
            item.img = '可回收垃圾'
            listKehuishou.push(item)
            break }
          case '有害垃圾处理站': {
            item.img = '有害垃圾'
            listYouhai.push(item)
            break }
        }
        this.tableData.push(item)
      })
      // eventBus.$emit('mapData_Toilet', this.tableData)
      eventBus.$emit('mapData_Factory', [listChuyu, listQita, listKehuishou, listYouhai])
      // eventBus.$emit('mapData_Factory', this.tableData)
    },
    // 分页导航
    handlePageChange (currentPage) {
      this.currentPage = currentPage
      // console.log(this.currentPage)
      // this.$set(this.query, 'pageIndex', val);
      // this.getlistdata();
    },
    handleSizeChange (size) {
      this.pageSize = size
      console.log(this.pageSize)
    },
    // 放大图片
    bigImage (row) {
      this.srcBig = row.VehiclePicPath
      this.showBigDialogVisible = true
    },
    handleClose () {
      this.showBigDialogVisible = false
    },

    // 双击表格某一行
    dblClickRow (row) {
      eventBus.$emit('mapDBrowFactory', row)
    }
  }
}
</script>
<style>
.container {
  overflow-y: auto;
  height: calc(100% - 50px);
  border: 0px;
}
.el-col-6 {
  min-width: 400px;
  min-height: 50px;
}
.el-table th {
  height: 40px;
}

/* .el-upload--text {
  width: 300px;
} */

</style>
